﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Mesuro.GUI.Utilities {
	public class FileFormatRegistry {
		private static Dictionary<String, LinkedList<FileFormat>> catalogue = new Dictionary<string, LinkedList<FileFormat>>();
		public static void RegisterFormat( String name, String ext, params string[] categories ) {
			RegisterFormat( name, new String[] { ext }, categories );
		}
		public static void RegisterFormat( String name, String[] ext, params string[] categories ) {
			FileFormat ff = new FileFormat() { Name = name, Extensions = ext };
			foreach (string cat in categories) {
				LinkedList<FileFormat> list;
				if (!catalogue.TryGetValue( cat, out list ))
					catalogue.Add( cat, list = new LinkedList<FileFormat>() );
				list.AddLast( ff );
			}
		}

		public static LinkedList<FileFormat> GetFormats( string category ) {
			return catalogue[category];
		}

		public static string GetExtensionString( string category ) {
			StringBuilder sb = new StringBuilder();

			foreach (FileFormat ff in catalogue[category])
				foreach (string ext in ff.Extensions)
					sb.Append( "*." ).Append( ext ).Append( ';' );

			if (sb.Length > 0)
				sb.Length--;

			return sb.ToString();
		}

		public static string GetFilterString( string category ) {
			StringBuilder sb = new StringBuilder();

			foreach (FileFormat ff in catalogue[category]) {
				sb.Append( ff.Name ).Append( '|' );
				int len = sb.Length;
				foreach (string ext in ff.Extensions)
					sb.Append( "*." ).Append( ext ).Append( ';' );
				if (sb.Length > len)
					sb.Length--;
				sb.Append( '|' );
			}

			if (sb.Length > 0)
				sb.Length--;

			return sb.ToString();
		}
	}
	public class FileFormat {
		public String Name { get; set; }
		private string[] _ext;
		public IEnumerable<String> Extensions {
			get { return _ext; }
			set {
				List<string> tmp = new List<string>();
				foreach (string s in value) {
					int period = s.LastIndexOf( '.' );
					if (period < 0)
						tmp.Add( s );
					else
						tmp.Add( s.Substring( period ) );
				}
				_ext = tmp.ToArray();
			}
		}
	}
}
